//
//  XQBindAccountController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/27.
//

#import "XQBindAccountController.h"
#import "XQBindAccountHeaderView.h"
#import "XQAccountWalletCell.h"
#import "XQAccountOtherCell.h"

@interface XQBindAccountController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,copy) NSArray *dataSource;

@property (nonatomic,copy) NSArray *otherDataSource;

@property (nonatomic,copy) NSMutableDictionary *cardDic;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) XQButton *bottomButton;

@end

@implementation XQBindAccountController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
    [self makeConstraints];
    self.startInterval = [XQTimeTool nowTimeStamp];
    [self refreshData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopLocation];
}

- (void)makeUI {
    self.view.backgroundColor = kCardColor;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomButton];
}

- (void)makeConstraints {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 60);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 20);
        make.left.right.equalTo(@0);
    }];
}

- (void)refreshData {
    NSDictionary *dic = @{
        @"accommodate" : self.cardId
    };
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/asset"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            NSDictionary *accomplish = responseObject[@"accomplish"];
            self.dataSource = accomplish[@"concluded"];
            [self getOtherArrays];
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataSource.count) {
        return self.dataSource != self.otherDataSource ? 2 : 1;
    }else {
        return 0;
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = self.dataSource[indexPath.row];
    if ([dic[@"concept"] isEqualToString:@"cardType"]) {
        XQAccountWalletCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XQAccountWalletCell" forIndexPath:indexPath];
        [cell setSelectIndex:[self getWalletSelectIndex:dic[@"performed"] datas:dic[@"emissions"]]];
        [cell setTitles:dic[@"emissions"]];
        @weakify(self);
        cell.buttonHandle = ^(NSString * _Nonnull text) {
            @strongify(self)
            [self.cardDic setValue:text forKey:dic[@"concept"]];
        };
        return cell;
    }else {
        XQAccountOtherCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XQAccountOtherCell" forIndexPath:indexPath];
        [cell setDataSource:self.otherDataSource];
        @weakify(self);
        cell.endEditingHandle = ^{
            @strongify(self);
            [self.view endEditing:YES];
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        
    NSDictionary *dic = self.dataSource[indexPath.row];
    if ([dic[@"concept"] isEqualToString:@"cardType"]) {
        return 64;
    }else {
        return 20 + self.otherDataSource.count * 88;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XQBindAccountHeaderView *headerView = [[XQBindAccountHeaderView alloc] init];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 130;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

#pragma mark - setter

- (void)setTopTitle:(NSString *)topTitle {
    [self.navigationBar setTitle:topTitle];
}

#pragma mark - private

- (void )getOtherArrays {
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0;i < self.dataSource.count; i++) {
        NSDictionary *dic = self.dataSource[i];
        if ([dic[@"concept"] isEqualToString:@"cardType"]) {
            [self.cardDic setValue:dic[@"performed"] forKey:dic[@"concept"]];
            continue;
        }else {
            [arr addObject:dic];
        }
    }
    self.otherDataSource = arr;
}

- (void)clickNextButton {
    NSMutableDictionary *dic = @{
        @"accommodate" : self.cardId
    }.mutableCopy;
    
    if (self.cardDic) {
        NSString *key = self.cardDic.allKeys.firstObject;
        NSString *value = self.cardDic[key];
        [dic setValue:value forKey:key];
    }
    
    NSMutableDictionary *otherDic = [NSMutableDictionary dictionary];
    NSArray<UITableViewCell *> *visibleCells = [self.tableView visibleCells];
    for (UITableViewCell *cell in visibleCells) {
        if ([cell isKindOfClass:[XQAccountOtherCell class]]) {
            otherDic = ((XQAccountOtherCell *)cell).dataDic;
        }
    }
    
    if (otherDic.count > 0) {
        for (NSString *key in otherDic) {
            NSString *value = otherDic[key];
            [dic setValue:value forKey:key];
        }
    }
    
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/orbcomm"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [self reportRisk];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
        }
    }];
}

- (NSInteger)getWalletSelectIndex:(NSString *)text datas:(NSArray *)datas {
    if (!text) {
        return 0;
    }
    
    NSInteger index = 0;
    for (int i = 0; i < datas.count ; i++) {
        NSDictionary *dic = datas[i];
        if ([dic[@"chance"] isEqualToString:text]) {
            index = i;
            break;;
        }
    }
    return index;
}

- (void)reportRisk {
    [XQGoogleMarket reportRiskWithType:@"8" longitude:self.longitude latitude:self.latitude startTime:self.startInterval endTime:[XQTimeTool nowTimeStamp] orderId:@""];
}

#pragma mark - lazy

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = kCardColor;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [_tableView registerClass:[XQAccountWalletCell class] forCellReuseIdentifier:@"XQAccountWalletCell"];
        [_tableView registerClass:[XQAccountOtherCell class] forCellReuseIdentifier:@"XQAccountOtherCell"];
    }
    return _tableView;
}

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}

- (NSMutableDictionary *)cardDic {
    if (!_cardDic) {
        _cardDic = [NSMutableDictionary dictionary];
    }
    return _cardDic;
}

- (XQButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [[XQButton alloc] initWithTitle:@"Next"];
        @weakify(self);
        _bottomButton.onTapHandle = ^{
            @strongify(self);
            [self clickNextButton];
        };
    }
    return _bottomButton;
}


@end
